/************************************************************************************/
/*  Program name CAPFNDEXT_KFF_STRUCTURE.sql                                        */
/*  Creater:  NIP Karen (PCCW - UniHub)                                             */
/*************   History   *************************                                */
/* 8 FEB, 2005   NIP Karen         First created                                    */
/************************************************************************************/
ALTER SESSION SET NLS_DATE_FORMAT='YYYYMMDD HH24:MI:SS';
SET SERVEROUTPUT ON SIZE 1000000;

DECLARE
	lv_Prog_ID		VARCHAR2(100)	:=	'CAPFNDEXT_KFF_STRUCTURE';

	lv_Scc_Count	NUMBER	:=	0;
	lv_Err_Count	NUMBER	:=	0;
	lv_Err_Msg		VARCHAR2(500)	:=	'No Error';

	lv_FileName		VARCHAR2(100)	:=	'CAPFND_KFF_STRUCTURE.dat';
	lv_PathName		VARCHAR2(100)	:=	'/tmp';
	lv_UTL_File		UTL_FILE.File_Type;

	lv_NGO_Code		VARCHAR2(100);
	lv_NGO_Count	NUMBER;

	CURSOR Cur_F(p_NGO VARCHAR2) IS
	SELECT	F.ID_FLEX_NAME, 
			S.ID_FLEX_STRUCTURE_CODE, 
			ST.LANGUAGE, 
			ST.ID_FLEX_STRUCTURE_NAME,  
			ST.DESCRIPTION, 
			S.STRUCTURE_VIEW_NAME, 
			S.FREEZE_FLEX_DEFINITION_FLAG, 
			S.CROSS_SEGMENT_VALIDATION_FLAG, 
			S.ENABLED_FLAG, 
			S.FREEZE_STRUCTURED_HIER_FLAG, 
			S.DYNAMIC_INSERTS_ALLOWED_FLAG
	FROM	FND_ID_FLEXS				F, 
			FND_ID_FLEX_STRUCTURES		S, 
			FND_ID_FLEX_STRUCTURES_TL	ST
	WHERE	SUBSTR(ST.ID_FLEX_STRUCTURE_NAME,1,4)	=	p_NGO
	AND		S.APPLICATION_ID	=	ST.APPLICATION_ID
	AND		S.ID_FLEX_CODE		=	ST.ID_FLEX_CODE
	AND		S.ID_FLEX_NUM		=	ST.ID_FLEX_NUM
	AND		F.APPLICATION_ID	=	S.APPLICATION_ID
	AND		F.ID_FLEX_CODE		=	S.ID_FLEX_CODE
	ORDER BY	
			F.ID_FLEX_NAME, 
			S.ID_FLEX_STRUCTURE_CODE, 
			ST.LANGUAGE;

BEGIN
	lv_NGO_Code		:=	UPPER('&NGO_Code');

	SELECT	COUNT('A')
	INTO	lv_NGO_Count
	FROM	HR_ALL_ORGANIZATION_UNITS
	WHERE	SUBSTR(Name,4,4)	=	lv_NGO_Code;

	IF	lv_NGO_Count	>=	1	THEN
		lv_UTL_File		:=	UTL_FILE.FOpen(lv_PathName, lv_FileName, 'w');
		FOR C1 IN Cur_F(lv_NGO_Code) LOOP
			UTL_FILE.PUT_LINE(
				lv_UTL_File,
				C1.ID_FLEX_NAME||'|'||
				C1.ID_FLEX_STRUCTURE_CODE||CHR(9)||
				C1.LANGUAGE||CHR(9)||
				C1.ID_FLEX_STRUCTURE_NAME||CHR(9)||
				C1.DESCRIPTION||CHR(9)||
				C1.STRUCTURE_VIEW_NAME||CHR(9)||
				C1.FREEZE_FLEX_DEFINITION_FLAG||CHR(9)||
				C1.CROSS_SEGMENT_VALIDATION_FLAG||CHR(9)||
				C1.ENABLED_FLAG||CHR(9)||
				C1.FREEZE_STRUCTURED_HIER_FLAG||CHR(9)||
				C1.DYNAMIC_INSERTS_ALLOWED_FLAG
			);

			lv_Scc_Count	:=	lv_Scc_Count	+	1;
		END LOOP;
		UTL_FILE.FClose(lv_UTL_File);
	ELSE
		lv_Err_Count	:=	lv_Err_Count + 1;
		lv_Err_Msg		:=	lv_NGO_Code||': No such NGO exists';
	END IF;

	INSERT INTO CAPCNV_LOG(
		PROG_ID,
		PROCESS_DATE,
		RECORD_PROCESSED,
		RECORD_REJECTED,
		RECORD_EXTRACTED,
		ERR_MSG
	) VALUES (
		lv_Prog_ID,
		SYSDATE,
		lv_Scc_Count,
		lv_Err_Count,
		lv_Scc_Count-lv_Err_Count,
		lv_Err_Msg
	);

	COMMIT;
END;
/
